package com.ourhours.message.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ourhours.link.annotation.Permission;
import com.ourhours.link.dto.UserInfoDto;
import com.ourhours.message.common.BaseResult;
import com.ourhours.message.domain.Template;
import com.ourhours.message.enums.SmsTypeEnum;
import com.ourhours.message.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dalong.wang
 * @since 2018-03-20
 */
@Controller
@RequestMapping("/template")
@Slf4j
public class TemplateController extends BaseController {
    @Autowired
    TemplateService templateService;

    @GetMapping("/list")
    @Permission("messageTemplate")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView("template/list");
        UserInfoDto user = getLoginUser();
        modelAndView.addObject("vendorId", user.getVendorId());
        return modelAndView;
    }

    @Permission("messageTemplateList")
    @PostMapping("/listPage")
    @ResponseBody
    public BaseResult listPage(Integer offset, Integer limit) {
        try {
            Template entity = new Template();
            UserInfoDto user = getLoginUser();
            entity.setDeleted(0L);
            entity.setVendorId(user.getVendorId());
            templateService.initTemplates(entity.getVendorId());
            EntityWrapper<Template> wrapper = new EntityWrapper<>(entity);
            wrapper.orderBy("id", false);
            Page<Template> page0 = new Page<>(offset / limit + 1, limit);
            Page<Template> page = templateService.selectPage(page0, wrapper);
            if (page.getRecords() != null && page.getRecords().size() > 0) {
                for (int i = 0; i < page.getRecords().size(); i++) {
                    if ("9999".equals(page.getRecords().get(i).getSmsType())) {
                        page.getRecords().get(i).setSmsType("自定义模板");
                        continue;
                    }
                    page.getRecords().get(i).setSmsType(SmsTypeEnum.fromCode(Integer.parseInt(page.getRecords().get(i).getSmsType())).getTitle());
                }
            }
            log.info("==> TemplateController.listPage查询短信模板列表成功,结果:{}", page);
            return BaseResult.success(page);
        } catch (Exception e) {
            log.error("==> EmailSendController.listPage查询短信模板列表失败，异常{}", e);
            return BaseResult.failure("查询失败!");
        }
    }

    @GetMapping("/edit")
    @Permission("messageTemplateEdit")
    public ModelAndView edit(Long id) {
        ModelAndView modelAndView = new ModelAndView("template/edit");
        Template entity = templateService.getTemplateById(id);
        modelAndView.addObject("template", entity);
        return modelAndView;
    }

    @PostMapping("/update")
    @ResponseBody
    @Permission("messageTemplateUpdate")
    public BaseResult update(Template entity) {
        try {
            if (entity == null || entity.getId() == null) {
                log.error("==>TemplateController.update 接收到的数据为空：{}", entity);
                return BaseResult.failure("-1", "接收到的数据为空");
            }
            UserInfoDto user = getLoginUser();
            entity.setUpdateTime(new Date());
            entity.setUpdateUser(user.getUserName());
            entity.setSysVersion(entity.getSysVersion() + 1);
            templateService.updateById(entity);
            templateService.setTemplateByIdCache(entity);
            templateService.setTemplateByTypeCache(entity);
            log.info("==> TemplateController.update 更新模板成功，参数:{}", entity);
            return BaseResult.success("更新模板成功!", entity);
        } catch (Exception e) {
            log.error("==>TemplateController.update 保存模板异常：{}", e);
            return BaseResult.failure("-1", "更新模板异常:" + e.getMessage());
        }
    }

    @GetMapping("/add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView("template/add");
        UserInfoDto user = getLoginUser();
        modelAndView.addObject("vendorId", user.getVendorId());
        return modelAndView;
    }

    @PostMapping("/save")
    @ResponseBody
    public BaseResult save(String content) {
        try {
            UserInfoDto user = getLoginUser();
            Template entity = new Template();
            entity.setDeleted(0L);
            entity.setVendorId(user.getVendorId());
            entity.setSmsType("9999");
            entity.setContent(content);
            entity.setSysVersion(1);
            entity.setUpdateTime(new Date());
            entity.setUpdateUser(user.getUserName());
            entity.setCreateTime(new Date());
            entity.setCreateUser(user.getUserName());
            boolean result = templateService.insert(entity);
            log.info("==> TemplateController.save 保存短信模板成功，参数:{},结果:{}", entity, result);
            return BaseResult.success("保存短信模板成功!", entity);
        } catch (Exception e) {
            log.error("==>TemplateController.save 保存短信模板异常：{}", e);
            return BaseResult.failure("-1", "保存短信模板异常:" + e.getMessage());
        }
    }
}

